﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NesEmu.Core;

namespace NesEmu.Console
{
    public partial class FrmDirFileList : Form
    {
        public FrmDirFileList()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (File.Exists("directory.settings"))
            {
                var selectedDirectory = File.ReadAllText("directory.settings");
                if (Directory.Exists(selectedDirectory))
                {
                    LoadDirectory(selectedDirectory);
                }
            }
        }

        private void LoadDirectory(string directory)
        {
            txtDir.Text = directory;
            btnBrowse.Enabled = false;
            lv.Items.Clear();
            backgroundWorker.RunWorkerAsync(directory);
        }

        public string? SelectedFileName
        {
            get
            {
                if (lv.SelectedItems.Count == 0)
                {
                    return null;
                }

                return lv.SelectedItems[0].Tag as string;
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (folderDlg.ShowDialog(this) == DialogResult.OK)
            {
                LoadDirectory(folderDlg.SelectedPath);
            }
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (e.Argument is null)
            {
                return;
            }

            var selectedDirectory = (string)e.Argument;
            foreach (var fileName in Directory.EnumerateFiles(selectedDirectory, "*.nes", SearchOption.AllDirectories))
            {
                backgroundWorker.ReportProgress(0, fileName);
            }
        }

        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.UserState is not null)
            {
                var curFileName = (string)e.UserState;
                var lvi = new ListViewItem(Path.GetFileName(curFileName))
                {
                    ImageKey = @"game"
                };

                try
                {
                    var cartridge = new Cartridge(curFileName);
                    var mapperInfo = Emulator.GetRegisteredMapperInfo()
                        .FirstOrDefault(x => x.Number == cartridge.Mapper);
                    if (mapperInfo is not null)
                    {
                        lvi.SubItems.Add(mapperInfo.Name);
                        lvi.ForeColor = SystemColors.ControlText;
                        lvi.Group = lv.Groups["lvgSupportedRoms"];
                    }
                    else
                    {
                        lvi.SubItems.Add($"Unknown: {cartridge.Mapper}");
                        lvi.ForeColor = SystemColors.GrayText;
                        lvi.Group = lv.Groups["lvgUnsupportedRoms"];
                    }

                    lvi.SubItems.Add(Path.GetDirectoryName(curFileName));
                    lvi.Tag = curFileName;
                    lv.Items.Add(lvi);
                }
                catch (Exception exception)
                {
                    System.Console.WriteLine(exception);
                }
            }
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnBrowse.Enabled = true;
            File.WriteAllText("directory.settings", txtDir.Text);
        }

        private void lv_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            var listViewItem = lv.GetItemAt(e.X, e.Y);
            if (listViewItem is not null)
            {
                DialogResult = DialogResult.OK;
                Close();
            }
        }
    }
}
